package agent

import (
	"fmt"
	"io"
	"net/http"
	"os"

	"gitee.com/liuxuezhan/ar-platform/base-common/result"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 报表下载
func AgentReportDownHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.DownRequest
		if err := httpx.Parse(r, &req); err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		fileName := req.FilePath
		file, err := os.Open(fileName)
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}
		defer file.Close()

		w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))

		_, err = io.Copy(w, file)
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}
	}
}
